/*
 * AGENT SHERPA
 *  
 * Assignement 2 of the Agent Oriented Software Engineering Course
 * M.Sc. in Advanced Software Engineering (Part-time)
 * University College Dublin www.ucd.ie
 *
 * Copyright (c) 2007 Chris Walsh, Aidan Morrisy and Iain Hull.
 * All rights reserved.
 */

package org.agentsherpa.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;


/**
 * Simple interface to load read the propeties file, holding map information.
 * 
 * @author iain
 */
public class MapProperties {
    private final Properties props = new Properties();
    private final File file;
    
    public MapProperties(String filename) throws MapPropertiesException {
        try {
            file = new File(filename);
            props.load(new FileInputStream(file));
        }
        catch (FileNotFoundException e) {
            throw new MapPropertiesException("Unable to load specified file " + filename, e);
        }
        catch (IOException e) {
            throw new MapPropertiesException("IO error reading specified file " + filename, e);
        }
    }
    
    public URL getMapImageFile() throws MapPropertiesException {
        return getUrlProperty("map.image");
    }

    public URL getBackgroundImageFile() throws MapPropertiesException {
        return getUrlProperty("background.image");
    }

    public int getZoom() throws MapPropertiesException {
        return getIntProperty("map.zoom");
    }

    private URL getUrlProperty(String name) throws MapPropertiesException {
        testHasProperty(name);
        try {
            File f = new File (file.getParentFile(), props.getProperty(name));
            return new URL("file:" + f.toString());
        }
        catch (MalformedURLException e) {
            throw new MapPropertiesException("Invalid url for " + name + " value " + props.getProperty(name), e);
        }
    }

    private void testHasProperty(String name) throws MapPropertiesException {
        if (!props.containsKey(name)) {
            throw new MapPropertiesException(file + " does not contain property " + name);
        }
    }

    private int getIntProperty(String name) throws MapPropertiesException {
        testHasProperty(name);
        try {
            return Integer.parseInt(props.getProperty(name));
        }
        catch (NumberFormatException e) {
            throw new MapPropertiesException("Invalid number for " + name + " value " + props.getProperty(name), e);
        }
     }
}
